package thread.java20230106;

public class MyBlockQueue {
    int head = 0;
    int tail = 0;
    int[] arr;//通过构造函数, 传递队列长度, 再进行初始化
    int size = 0;
    int len;

    public MyBlockQueue(int len) {
        arr = new int[len];
        this.len = len;
    }

    /**
     * 放数据
     *
     * @param num
     */
    public synchronized void put(int num) throws InterruptedException {
        //当队列满了, 就阻塞, 直到其他线程取出数据
        while (size == len) {
            this.wait();
        }
        arr[tail] = num;
        tail++;
        size++;
        if (tail >= len) {
            tail = 0;
        }
        //放数据之后, 就唤醒取数据的线程
        this.notify();
    }

    /**
     * 取数据
     *
     * @return
     */
    public synchronized int take() throws InterruptedException {
        //队列空的时候, 线程阻塞
        while (size == 0) {
            this.wait();
        }
        int num = arr[head];
        head++;
        size--;
        if (head >= len) {
            head = 0;
        }
        this.notify();
        return num;
    }

}
